package com.ifnk.portaljava.dapWeb.dapweb;
/**
 * <p>Title: 返回二进制对应的十六进制信息类</p>
 *
 * <p>Description: </p>
 *
 * <p>Copyright: Copyright (c) 2010</p>
 *
 * <p>Company: </p>
 *
 * @author WenSheng.Song.hlyt@gmail.com
 * @version 1.0
 */

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class ReadBinaryUtil {
	//注意接收的原始数据时去了包头20个字节和2个补码字节的真实的pkt的数据
	public CDRBean readBinaryToString(byte[] data,CDRBean cdrBean) throws IOException {
		String pktStr = "";
		for(int i=0;i<data.length;i++){
			pktStr += Integer.toHexString(data[i]&0xFF)+"; ";
		}
		//十六进制的数据
		StringBuilder binary = new StringBuilder();
		StringBuilder text = new StringBuilder();
		byte temp = 0;
		for(int i=0;i<data.length;i++) {
			temp = data[i];
			// 以十六进制的无符号整数形式返回一个字符串表示形式。
			String str = Integer.toHexString(temp);
			if(str.length() == 8) {//去掉补位的f
				str = str.substring(6);
			}
			if(str.length() == 1) {
				str = "0"+str;
			}
			binary.append(str.toUpperCase());
			//转换成ascii码
			String ascii = "";
			if(temp>34 && temp <127) {
				char c = (char)temp;
				ascii = c+"";
			}else{
				ascii = ".";
			}
			text.append(ascii);
		}
		//计算行数
		int line = (text.toString().length() % 16 == 0) ? text.toString().length()/16 : text.toString().length()/16 + 1;
		//System.out.println(line);
		StringBuilder lines = new StringBuilder();
		for(int i=0;i<line;i++) {
			String li = Integer.toHexString(i)+"0";
			if(li.length() == 2){
				li = "00"+li;
			}
			if(li.length() == 3) {
				li = "0"+li;
			}
			lines.append(li);
		}
		cdrBean.setLine(lines.toString());
		cdrBean.setBinary(binary.toString());
		cdrBean.setText(text.toString());
	//	loger.info("readBinaryToString: " + pktStr);
//		loger.info("binary " + cdrBean.getBinary());
//		loger.info("line " + cdrBean.getLine());
		return cdrBean;
	}
	//测试用
	public static void main(String[] args) {
		byte[] packet = new byte[132];
		try {
			DataInputStream in = new DataInputStream(new FileInputStream(new File("C:\\Users\\HLYT\\Desktop\\pkt.dat")));
			in.read(packet);
			byte[] data = new byte[112];
			System.arraycopy(packet, 20, data, 0, 112);
			ReadBinaryUtil util = new ReadBinaryUtil();
			CDRBean cdrBean = new CDRBean();
			util.readBinaryToString(data, cdrBean);
			//int line = (100 % 16 == 0) ? 100/16 : 100/16 + 1;
			//System.out.println(line+" ");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}
